﻿using System;
using System.Activities.Tracking;
using System.Linq;
using System.Text;
using log4net;

namespace Reactor.Workflow.Tracking
{
    public class LogTrackingParticipant : TrackingParticipant
    {
        private readonly ILog _logger;

        public LogTrackingParticipant(ILog logger)
        {
            if (logger == null) throw new ArgumentNullException("logger");

            _logger = logger;
        }

        protected override void Track(TrackingRecord record, TimeSpan timeout)
        {
            if(record is WorkflowInstanceRecord)
                TrackWorkflowInstanceRecord((WorkflowInstanceRecord) record);
            else if(record is ActivityStateRecord)
                TrackActivityStateRecord((ActivityStateRecord)record);
            else if(record is CustomTrackingRecord)
                TrackCustomTrackingRecord((CustomTrackingRecord) record);
        }

        private void TrackCustomTrackingRecord(CustomTrackingRecord record)
        {
            if (!record.Data.Any()) return;
            
            var sb = new StringBuilder();
            foreach (var data in record.Data)
                sb.Append(string.Format("[Name: {0} Value: {1}] ", data.Key, data.Value));

            _logger.DebugFormat("CustomTrackingRecord | Data: {0}", sb);
        }

        private void TrackActivityStateRecord(ActivityStateRecord record)
        {
            var variables = record.Variables;
            StringBuilder vars = new StringBuilder();

            foreach (var variable in variables)
                vars.Append(String.Format("[Name: {0} Value: {1}] ", variable.Key, variable.Value));

            _logger.DebugFormat("ActivityStateRecord | Name: {0} State: {1} Variables: {2}", record.Activity.Name, record.State, vars);
        }

        private void TrackWorkflowInstanceRecord(WorkflowInstanceRecord record)
        {
            _logger.DebugFormat("WorkflowInstanceRecord | Id: {0} - State: {1}", record.InstanceId, record.State);
        }
    }
}
